package com.sxz.sbs.rx;

import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.applibrary.dialog.loading.LoadingDialog;
import com.sxz.sbs.base.BaseView;
import com.sxz.sbs.http.exception.ApiException;
import com.sxz.sbs.http.exception.LoginException;
import com.sxz.sbs.widget.StallAlertDialog;

import io.reactivex.subscribers.ResourceSubscriber;

/**
 * 订阅
 */

public abstract class RxSubscriber<T> extends ResourceSubscriber<T> {
    private BaseView mView;
    private boolean isLoading = false;
    public LoadingDialog mLoading;
    private Context context;
    private RxSubscriber(StallAlertDialog.OnPositiveListener onPositiveListener){
    }
    public RxSubscriber(BaseView view){
        this.mView = view;
    }
    public RxSubscriber(BaseView view,boolean isLoading){
        this.mView = view;
        this.isLoading = isLoading;
        context = view.getContext();
        mLoading= LoadingDialog.create(context).setCancellable(true).setDimAmount(0.5f);
        if (isLoading) {
            mLoading.show();
        }
    }
   /* public RxSubscriber(BaseView view, LoadingDialog.Style style){
        this.mView = view;
        context = view.getContext();
        this.isLoading = true;
        mLoading= LoadingDialog.create(context)
                .setStyle(style)
                .setWindowColor(Color.WHITE)
                .setCancellable(true)
                .setDimAmount(0.5f);
        mLoading.show();
    }*/

    @Override
    public void onComplete() {
        if (isLoading) {
           mLoading.dismiss();
            context = null;
            isLoading = false;
        }
    }

    @Override
    public void onError(Throwable e) {
        if (isLoading) {
            mLoading.dismiss();
            context = null;
            isLoading = false;
        }
        if (mView == null) {
            return;
        }
        if (!NetworkUtils.isConnected()) {
            mView.showError(3,mView.getContext().getResources().getString(R.string.network_error));
        } else if (e instanceof LoginException) {
            mView.loginAgain();
        } else if (e instanceof ApiException) {
            mView.showError(0,e.getMessage());
        } else if (e instanceof IllegalStateException) {
            mView.showError(2,"数据解析异常ヽ(≧Д≦)ノ");
        } else {
            mView.showError(4,"请求异常，请稍后再试");
            LogUtils.e("错误" + e.getMessage()+e.getCause()+"-"+e.toString());
        }
    }
}
